
# include "dfxFileLog.h"

namespace DFX
{
    FileLog::FileLog(UInt32 logLevel)
        : Log(logLevel), mLogFp(NULL)
    {
    }

    FileLog::~FileLog()
    {
        Close();
    }

    DFXRESULT FileLog::Open(const String &fileName)
    {
        mFileName = fileName;
        mLogFp = fopen(mFileName.c_str(), "w");

        if (mLogFp)
        {
            time_t t = time(0);
            tm *now = localtime(&t);

            fprintf(mLogFp, "DFX Game Engine [%02d/%02d/%04d %02d:%02d:%02d]\n", 
                now->tm_mday, now->tm_mon+1, now->tm_year + 1900, now->tm_hour, now->tm_min, now->tm_sec);
            fprintf(mLogFp, "============================================\n\n");

            return DFX_SUCCESS;
        }
        
        return DFX_CREATEFAILED;
    }

    DFXRESULT FileLog::Close()
    {
        if (mLogFp)
        {
            fclose(mLogFp);
            mLogFp = NULL;

            return DFX_SUCCESS;
        }

        return DFX_NULLPTR;
    }

    void FileLog::Write(LOG_TYPE logType, const String &fileName, UInt32 lineNo, char *format, ...)
    {
        char type[MAXBUF] = "";

        if (!mLogFp)
            return;

        time_t t = time(0);
        tm *now = localtime(&t);

        if (logType == LOG_TYPE_ERROR)
            strcpy(type, "Error");
        else if (logType == LOG_TYPE_WARNING)
            strcpy(type, "Warning");

        fprintf(mLogFp, "[%02d:%02d:%02d][%s, %ld]: ", now->tm_hour, now->tm_min, 
            now->tm_sec, fileName.c_str(), lineNo);

        va_list arg;
        
        va_start(arg, format);
        vfprintf(mLogFp, format, arg);
        va_end(arg);

        fprintf(mLogFp, "\n");
        fflush(mLogFp);
    }
}